package result

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"log"
	"sync"
)

type wsResult struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
}

var wsMutex sync.Mutex

func WsOk(messageType int, ws *websocket.Conn, data any) {
	var rst = wsResult{
		Code:    0,
		Message: "SUCCESS",
		Data:    data,
	}
	bytes, err := json.Marshal(&rst)
	if err != nil {
		log.Println(err)
		return
	}
	wsMutex.Lock()
	err = ws.WriteMessage(messageType, bytes)
	wsMutex.Unlock()
	if err != nil {
		log.Println(err)
		return
	}
}

func WsFail(messageType int, ws *websocket.Conn, code int, message string) {
	var rst = wsResult{
		Code:    code,
		Message: message,
		Data:    "",
	}
	bytes, err := json.Marshal(&rst)
	if err != nil {
		log.Println(err)
		return
	}
	wsMutex.Lock()
	err = ws.WriteMessage(messageType, bytes)
	wsMutex.Unlock()
	if err != nil {
		log.Println(err)
		return
	}
}
